package org.example.what_mall.interceptor;

import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.example.what_mall.config.JWTConfig;
import org.example.what_mall.enums.UserRole;
import org.example.what_mall.exception.GlobalCode;
import org.example.what_mall.exception.GlobalException;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Objects;

@Component
public class AdminInterceptor implements HandlerInterceptor {
    @Resource
    private JWTConfig jwtConfig;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if(Objects.equals(request.getMethod(), "OPTIONS")){
            return true;
        }
        String token = request.getHeader("token");
        if (token == null) {
            throw new GlobalException(GlobalCode.UNAUTHORIZED);
        }
        Integer role = jwtConfig.decode(token).getClaim("role").asInt();
        if(role != UserRole.ADMIN_USER.getCode()) {
            throw new GlobalException(GlobalCode.UNAUTHORIZED);
        }
        return true;
    }
}
